package com.test.kf21th02.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.test.kf21th02.model.Category;
import com.test.kf21th02.model.CategoryDTO;
import com.test.kf21th02.model.News;
import com.test.kf21th02.service.ICategoryService;
import com.test.kf21th02.service.INewsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author zsy
 * @since 2025-11-04
 */
@Controller
@RequestMapping("/news")
public class NewsController {
    @Autowired
    private INewsService newsService;
    @Autowired
    private ICategoryService categoryService;

    @ModelAttribute//非请求处理方法(他会在所有请求处理方法之前先运行)
    public void before(Model model){
        int a=10;
        List<Category> categories = categoryService.list();
        model.addAttribute("cs", categories);
    }



    @RequestMapping("/list")//请求处理方法
    public String newsList(CategoryDTO dto, Model model){
        List<News> news = newsService.queryAll(dto);
//        List<Category> categories = categoryService.list();

        model.addAttribute("ns", news);
//        model.addAttribute("cs", categories);
        return "index";
    }
    @RequestMapping("/goAdd")
    public String toSave(){
        return "addNews";
    }
    @RequestMapping("/save")
    public String saveNews(String title,Integer categoryId){
        News n=new News();
        n.setTitle(title);
        boolean save = newsService.save(n);
        CategoryDTO dto=new CategoryDTO();
        dto.setCategoryId(categoryId);
        dto.setNewsId(n.getNewsId());
        newsService.saveNewsCategory(dto);
        return "redirect:list";

    }

    @RequestMapping("/toAddType")
    public String toSaveType(){
        return "addType";
    }
    @RequestMapping("/saveType")
    public String saveType(Category category,Model model){
        QueryWrapper query=new QueryWrapper();
        query.eq("category_name",category.getCategoryName());
        Category c = categoryService.getOne(query);
        if(c==null){
            categoryService.save(category);
            return "redirect:goAdd";
        }else{
            model.addAttribute("msg","已存在同样的内容");
            return "addType";
        }
    }

}
